package com.wlw.admin.openeye.mvp.presenter

import com.wlw.admin.openeye.base.BasePresenter
import com.wlw.admin.openeye.mvp.contract.SearchContract
import com.wlw.admin.openeye.mvp.model.SearchModel
import com.wlw.admin.openeye.mvp.model.bean.HomeBean
import com.wlw.admin.openeye.net.exception.ExceptionHandle

class SearchPresenter : BasePresenter<SearchContract.View>(), SearchContract.Presenter {
    private var nextUrl: String? = null
    private val searchModel by lazy {
        SearchModel()
    }


    override fun requestHotWordData() {
        checkViewAttached()
        mRootView?.apply {
            closeSoftKeyboard()
            showLoading()
        }
        addSubscription(searchModel.requestHotWordData().subscribe({
            mRootView?.apply {
                setHotWordData(it)
            }
        }, { t ->
            mRootView?.apply {
                showError(ExceptionHandle.handleException(t), ExceptionHandle.errorCode)
            }

        }))
    }

    override fun querySearchData(words: String) {
        checkViewAttached()
        mRootView?.apply {
            closeSoftKeyboard()
            showLoading()
        }
        addSubscription(searchModel.getSearchResult(words).subscribe({
            mRootView?.apply {
                dismissLoading()
                if (it.count > 0 && it.itemList.size > 0) {
                    nextUrl = it.nextPageUrl
                    setSearchResult(it)
                } else {
                    setEmptyView()
                }
            }
        }, { t ->
            mRootView?.apply {
                dismissLoading()
                showError(ExceptionHandle.handleException(t), ExceptionHandle.errorCode)
            }

        }))


    }

    override fun loadMoreData() {
        checkViewAttached()
        nextUrl?.let {
            addSubscription(searchModel.loadMoreData(it).subscribe({
                mRootView?.apply {
                    nextUrl = it.nextPageUrl
                    setSearchResult(it)
                }
            }, { t ->
                mRootView?.apply {
                    showError(ExceptionHandle.handleException(t), ExceptionHandle.errorCode)
                }
            }))
        }
    }
}